﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using log4net;
using System.IO;
using System.ServiceModel;

using iLangl.Transport.Extensions;
using iLangl.Transport.Communication;

namespace iLangl.Transport
{
	[ServiceBehavior(UseSynchronizationContext = false)]
	public class WCFTransport : ITransport
	{
		private static ILog log = LogManager.GetLogger(typeof(WCFTransport));

		public void SendRequest(UploadRequest request)
		{
			log.DebugFormat(
			"SendRequest called Incoming Package (Id='{0}' Size={1})",
			request.PackageId,
			request.PackageSize);

			ValidateRequest(request);

			String uploadFilePath = GetFilePath(request);

			log.DebugFormat("Begin Saving Package");

			request.PackageData.WriteToFile(uploadFilePath);

			FileInfo uploadedFile = new FileInfo(uploadFilePath);

			//Package Size Check
			if (request.PackageSize != uploadedFile.Length)
			{
				String corruptedFilePath = Path.Combine(
				"",//TransportConfiguration.Instance.CorruptedPackageFolder, TODO
				request.PackageId);

				File.Move(uploadFilePath,corruptedFilePath);
				
				throw new FaultException<InvalidPackageSize>(new InvalidPackageSize(Convert.ToInt64(uploadedFile.Length)));
			}

			// If Package verivied we add zip exension and this will publish this package for robots
			Path.ChangeExtension(uploadFilePath, "ZIP");
		}

		private String GetFilePath(UploadRequest request)
		{
			return Path.Combine(
				TransportConfiguration.Instance.IncomePackageFolder,
				request.DeliveredFileName);
		}

		private String GetFilePath(UploadLightRequest request)
		{
			return Path.Combine(
				TransportConfiguration.Instance.IncomePackageFolder,
				request.DeliveredFileName);
		}


		private static void ValidateRequest(UploadRequest request)
		{
			if (String.IsNullOrEmpty(request.PackageId))
			{
				throw new FaultException<InvalidArgumentFault>(new InvalidArgumentFault("PackageId"));
			}

			if (String.IsNullOrEmpty(request.DeliveredFileName))
			{
				throw new FaultException<InvalidArgumentFault>(new InvalidArgumentFault("DeliveredFileName"));
			}

		}


		public UploadLightResponse SendRequestSync(UploadLightRequest request)
		{

			
			UploadLightResponse response = new UploadLightResponse();

			IPackage package = Facade.Instance.PackageManager.DispatchPackageFromString(request.PackageData);

			try
			{

				Facade.Instance.PackageManager.ExecutePackage(package);

				List<String> result = new List<string>();

				foreach (IPackage responsepackage in package.ResponsePackages)
				{
					result.Add(responsepackage.PackageBody);
				}

				response.Responses = result.ToArray();

		

				Facade.Instance.PackageManager.PatchPackageToFile(TransportConfiguration.Instance.DispatchedPackageFolder, package);
			}
			catch (System.Exception ex)
			{
			

				Facade.Instance.PackageManager.PatchPackageToFile(TransportConfiguration.Instance.DispatchedPackageFolder, package);

				throw ex;
			}

			return response;
		}
	}
}
